package com.watf.functions.gs;

import org.testng.Assert;
import org.testng.Reporter;

import com.thoughtworks.selenium.Selenium;
import com.watf.functions.core.DefaultBasicFuncs;
import com.watf.functions.core.DefaultConfigUtil;
import com.watf.pages.gs.MainFrame;
import com.watf.pages.gs.Workflows;

import java.io.File;

/*
 * FileName: WorkflowsFuncs.java
 * Author:Jester
 * Methods: importWorkflow() 
 * 
 * History:
 * Date       Comments       Updater
 * 2011-6-28   First Draft    Jester
 */
public class WorkflowsFuncs extends DefaultBasicFuncs {

	/*
	 * This method used to import the workflow from the exist .xml file.
	 * Author:Jester
	 */
	private static final String MAIN_TABLE = "//div[@id='contentLayer']/form/p/table/tbody/tr[2]/td/table/tbody";
	private static final String AUTO_SUFFIX = "_en_US_fr_FR";
	
	/**
	 * Goto 'Workflows' page
	 * @param selenium
	 * @author bear
	 */
	public void gotoWorkflowsPage( Selenium selenium ) {
		selenium.click( MainFrame.Setup_MENU );
		selenium.click( MainFrame.Workflows_SUBMENU );
		selenium.waitForPageToLoad( CommonFuncs.SHORT_WAIT );
		Assert.assertEquals( selenium.getTitle(), Workflows.TITLE );
	}
	
	//note: this function is related to specified computer, and need to improve in future
	
	public void exportWorkflow(Selenium selenium,String workflowTemplate) throws Exception
	{
		// The default download directory of Firefox, differs between PCs.
		String downloadDir = "C:\\Users\\bear\\Downloads\\";
		String saveHandler = DefaultConfigUtil.getConfigData( "Base_Path" ) + "Tools\\gs\\firefox_save.exe";
		
		boolean check = selectRadioButtonFromTable(selenium,MAIN_TABLE,workflowTemplate);
		Assert.assertTrue( check, "Can not find the workflow template to export!" );
		
		/* Before download the file, make sure it does not exist in local machine */
		String fullPath = downloadDir + workflowTemplate + ".xml";
		File file = new File( fullPath );
		if( file.isFile() ) {
			file.delete();
		}
		
		selenium.click(Workflows.Export_BUTTON);
		// Use Autoit to handle the save files dialog
		Process p = Runtime.getRuntime().exec( saveHandler );
		p.waitFor();
		// Check if the file download rightly
		Assert.assertTrue( new File( fullPath ).isFile() );
		
	}
	
	public String importWorkFlow(Selenium selenium,String iFile,String ImportProfiles) throws Exception
	{
		selenium.click(Workflows.Import_BUTTON);
		selenium.waitForPageToLoad(CommonFuncs.SHORT_WAIT);
		selenium.type(Workflows.FileToImport_TEXT_FIELD, iFile);

		String[] iImportProfiles = ImportProfiles.split(",");
		String iWorkflowName = null;
		
		for (String iImportProfile :  iImportProfiles)
		{
			String[] ivalue = iImportProfile.split("=");
			String iFieldName = ivalue[0].trim();
			String iFieldValue = ivalue[1].trim();
			
			if (iFieldName.equals("name"))
			{
				selenium.type(Workflows.Name_TEXT_FIELD_IMPORT, iFieldValue);
				iWorkflowName=iFieldValue;
				
			}
			else if(iFieldName.equals("project"))
			{
				selenium.select(Workflows.Project_SELECT, iFieldValue);
			}
			else if(iFieldName.equals("sourcelocale"))
			{
				selenium.select(Workflows.SourceLocale_SELECTION, iFieldValue);
				iWorkflowName += "_" + iFieldValue.substring( iFieldValue.indexOf( '[') + 1, iFieldValue.indexOf( ']' ) );
			}
			else if(iFieldName.equals("targetlocale"))
			{
				selenium.addSelection(Workflows.TargetLocale_SELECTION, iFieldValue);
				iWorkflowName += "_" + iFieldValue.substring( iFieldValue.indexOf( '[') + 1, iFieldValue.indexOf( ']' ) );
			}
			else
			{
				Assert.assertTrue( false, "The field name "+iFieldName+" can't be found on this page! Please verify it first." );
			}
		}
		
		selenium.click(Workflows.Add_BUTTON);
		selenium.click(Workflows.Save_BUTTON);
		
		if (selenium.isAlertPresent())
		{
			selenium.getAlert();
			selenium.click(Workflows.Cancel_BUTTON);
			if (selenium.isConfirmationPresent())
			{
				selenium.getConfirmation();
			}
			selenium.waitForPageToLoad(CommonFuncs.SHORT_WAIT);
		}
		else
		{
			selenium.waitForPageToLoad(CommonFuncs.SHORT_WAIT);
		}
		
		Reporter.log( "The imported workflow is " + iWorkflowName  );
		Assert.assertTrue(isPresentInTable(selenium, Workflows.Workflows_TABLE, iWorkflowName));
		return iWorkflowName;
	}

	public void duplicateWorkFlow(Selenium selenium,String iFile, String workflowTemplate) throws Exception 
	{
		
		boolean check = selectRadioButtonFromTable(selenium,MAIN_TABLE,workflowTemplate);
		if (!check)
		{
            Assert.assertTrue( false, "Cannot find the workflow template to duplicate!" );
		}
		selenium.click(Workflows.Duplicate_BUTTON);
		selenium.waitForPageToLoad( CommonFuncs.SHORT_WAIT );
		
		selenium.type(Workflows.Name_TEXT_FIELD_DUPLICATE, iFile);
		selenium.select(Workflows.SourceLocle_SELECTION_DUPLICATE,DefaultConfigUtil.getCommonData("en_US"));
		selenium.select(Workflows.TargetLocale_SELECTION_DUPLICATE,DefaultConfigUtil.getCommonData("fr_FR"));
		selenium.click(Workflows.Add_BUTTON_DUPLICATE);
		selenium.click(Workflows.Save_BUTTON_DUPLICATE);
		
		String workflowName = iFile + AUTO_SUFFIX;
		boolean selected = isPresentInTable(selenium, MAIN_TABLE, workflowName );		
		if (selected)
		{
			Reporter.log( "Duplicated workflow " + workflowName + " is added.");
		} else {
			Assert.assertTrue( false, "Failed to create duplicated workflow " + workflowName + "." );
		}
	}
	
	public void removeWorkFlow( Selenium selenium, String workflow ) throws Exception
	{
		workflow += AUTO_SUFFIX;
		boolean check = selectRadioButtonFromTable(selenium,MAIN_TABLE,workflow);
		if (!check)
		{
			Assert.assertTrue( false, "Cannot find the workflow to remove!" );
		}
		
		selenium.click(Workflows.RemoveWF_BUTTON);
		boolean actual = selenium.getConfirmation().equals("Are you sure you want to remove this Workflow?");
    	Assert.assertTrue( actual, "The confirmation for removing workflow is not right!" );
        
        Assert.assertFalse( isPresentInTable( selenium, MAIN_TABLE, workflow ), 
        		"Failed to remove workflow" + workflow + "." );
        Reporter.log( "Workflow " + workflow + " is removed rightly!" );
	}
}
